<template>
  <div>
    <FormPanel ref="topFilter" :list="topFilterList" @filterChange="handleSearch" @onCollapse="collapseHandle" :isSubmitBtn="false"></FormPanel>
    <FilterTable
      ref="table"
      columnsRef="newBorrowOrderRef"
      :columns="columns"
      :fetchapi="fetchapi"
      :params="fetchParams"
      :datakey="'rows'"
      :onCellChange="change"
      :onSyncTableData="handleSyncTableData"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls">
        <el-button size="small" type="primary" @click="showNewTools">新增工具</el-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="showPanel" title="新增工具" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <toolsChoose @close="showPanel = false" @confirm="confirm" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import { getUser, getUserId, getOwnerCode } from '@/assets/js/auth';
import toolsChoose from './toolsChoose';
import { exportExcelFile, arrayObjDeWeight } from '@/utils/index';
import { getAllUser } from '@/api/customerRepair/usedCarVisit/resultEntry';
import { queryUnitCode } from '@/api/repair/batchEventManagement/activityDistribution';
import { confirmAction, notifyAction } from '@/utils';
import { getStroageList } from '@/api/part/partOutbound/partBreak';

export default {
  mixins: [dictionary],
  components: {
    toolsChoose
  },
  mounted() {
    this.getAllUser();
    this.getUnit();
    this.searchstore();
  },
  data() {
    return {
      topFilterList: this.createTopFIlterList(),
      columns: this.createTableColumns(),
      fetchapi: () => {},
      fetchParams: { xhrAbort: true },
      showPanel: false,
      isShowSearchBorrowOrder: false,
      loading: false,
      deleteList: [],
      dataSource: [],
      syncTableData: [] // 同步的table数据
    };
  },
  methods: {
    createTopFIlterList() {
      return [
        {
          type: 'INPUT',
          label: '借用单号',
          fieldName: 'borrowNo',
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.isShowSearchBorrowOrder = true;
                }}
              ></el-button>
            );
          },
          disabled: true
        },
        {
          type: 'INPUT',
          label: '借用日期',
          fieldName: 'borrowDate',
          initialValue: moment().format('YYYY-MM-DD'),
          disabled: true
        },
        {
          type: 'SELECT',
          label: '经手人',
          fieldName: 'outUser',
          initialValue: getUserId(),
          itemList: [],
          disabled: true
        },
        {
          type: 'SELECT',
          label: '借用人',
          fieldName: 'borrowUser',
          filterable: true,
          change: () => {
            this.change();
          },
          itemList: []
        },
        {
          type: 'INPUT',
          label: '备注',
          change: () => {
            this.change();
          },
          fieldName: 'remarks'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deleteRow(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '工具代码',
          dataIndex: 'partNo',
          sorter: true
        },
        {
          title: '工具名称',
          dataIndex: 'partName',
          sorter: true
        },
        {
          title: '仓库名称',
          dictItems: [],
          dataIndex: 'storageCode',
          sorter: true
        },
        {
          title: '库位',
          dataIndex: 'storagePositionCode',
          sorter: true
        },
        {
          title: '单位',
          dataIndex: 'unitCode',
          filterType: 'checkbox',
          dictItems: [],
          sorter: true
        },
        {
          title: '借出数量',
          dataIndex: 'counts',
          filterType: 'number',
          min: 0,
          precision: 2,
          defaultEditable: true,
          editType: 'number',
          sorter: true,
          filter: true,
          editable: true
        }
      ];
    },
    async searchstore() {
      const res = await getStroageList();
      this.codeName = this.columns.find(x => x.dataIndex == 'storageCode').dictItems = this.columns.find(x => x.dataIndex == 'storageCode').filterItems = this.columns.find(
        x => x.dataIndex == 'storageCode'
      ).editItems = res.data.map(x => ({
        value: x.STORAGE_CODE,
        text: x.STORAGE_NAME
      }));
    },
    change(val) {
      this.$emit('change');
      console.log('changeval:::', val);
    },
    collapseHandle() {
      this.nextTick(() => {
        this.refs.table.EXECUTE_RESET_HEIGHT();
      });
    },
    showNewTools() {
      this.showPanel = true;
    },
    deleteRow(val) {
      console.log('deleteval', val);
      this.deleteList[0] = val;
      this.$refs.table.EXECUTE_DELETE(this.deleteList);
      this.$notify({
        title: '提示信息',
        message: '删除成功',
        type: 'success'
      });
    },
    // 点击搜索
    handleSearch() {},
    // 同步table数据
    handleSyncTableData(list) {
      this.syncTableData = list;
    },
    confirm(val) {
      console.log(val);
      let flag = true;
      if (val.length == 0) {
        this.$notify({
          title: '提示信息',
          message: '请选择数据',
          type: 'warning'
        });
        flag = false;
      }
      console.log('this.dataSource::', this.syncTableData);

      this.syncTableData.forEach(x => {
        val.forEach(y => {
          if (x['partNo'] === y['partNo'] && x['storageCode'] === y['storageCode']) {
            this.$notify({
              title: '提示信息',
              message: '添加工具已存在',
              type: 'warning'
            });
            flag = false;
          }
        });
      });
      if (flag) {
        this.$refs.table.EXECUTE_INSERT(val);
        this.$notify({
          title: '提示信息',
          message: '添加成功',
          type: 'success'
        });
      }
    },
    async getUnit() {
      const res = await queryUnitCode();
      console.log('getUnit res::', res);
      let data = arrayObjDeWeight(res.data, 'UNIT_CODE');
      this.columns.find(x => x.dataIndex == 'unitCode').dictItems = data.map(x => ({ value: x.UNIT_CODE + '', text: x.UNIT_NAME }));
    },
    async getAllUser() {
      const res = await getAllUser();
      let data = arrayObjDeWeight(res.data, 'userId'); // 人员去重(解决前端报错)
      this.topFilterList.find(item => item.fieldName === 'borrowUser').itemList = data.map(x => ({ value: x.userId + '', text: x.employeeName }));
      this.topFilterList.find(item => item.fieldName === 'outUser').itemList = data.map(x => ({ value: x.userId + '', text: x.employeeName }));
    }
  }
};
</script>

<style lang="less" scoped>
.btnWrap {
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
</style>
